import 'package:cave_flutter/model/base_source_model.dart';
import 'package:cave_flutter/utils/whl_avatar_utils.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/utils/whl_permission_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:cave_flutter/common/common_action.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';

import 'package:cave_flutter/model/image_model.dart';

import 'package:get/get.dart';
import './model/cave_model.dart';

class Create_caveLogic extends GetxController {
  List dataSource = [];
  CaveModel? caveModel;

  List<dynamic> personCategory = [];
  List<dynamic> officialCategory = [];
  List<dynamic> officialSecondCategory = [];
  ImageModel? imageModel;

  String officialCategoryActive = '';

  TextEditingController caveNameController = TextEditingController();
  TextEditingController contentController = TextEditingController();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    getPersonCategory();
    getOfficialCategory();
    setupAllData();
    CaveModel model = CaveModel(
        caveName: '', caveType: 0, caveCategories: '', caveCategoriesDesc: '');

    caveModel = model;
    update();
    // print(caveModel?.caveName);
  }

  String? avatarUrl = '';
  String? filePath;

  selectPhoto() {
    WhlPermissionUtil.reqStoragePermission(onSuccessAction: () async {
      List<AssetEntity>? resultList = await AssetPicker.pickAssets(Get.context!,
          pickerConfig: const AssetPickerConfig(
            requestType: RequestType.image,
            maxAssets: 1,
          ));
      if (resultList != null && resultList.isNotEmpty) {
        AssetEntity assetEntity = resultList.first;
        filePath = (await assetEntity.file)?.path;
        update();
        // onCheckPostBtnEnable();
        uploadImage(assetEntity);
      }
    });
  }

  uploadImage(AssetEntity? assetEntity) {
    imageModel = ImageModel(
      assetEntity: assetEntity,
    );
    uploadImageRequest(imageModel!, callBack: (model, isSuccess) {
      if (isSuccess) {
        avatarUrl = model.imageUrl;
        update();
      } else {
        imageModel = null;
        MyToast.show('上传失败');
      }
    });
  }

  setupAllData() {
    List data = [];
    BaseItemModel headModel = BaseItemModel(
        title: "设置Cave头像",
        hitString: "实名认证才可创建，与学生有关的圈子需要上传学生证照片",
        requestKey: "",
        itemType: BaseItemTypeENUM.ENUM_headerCell);

    BaseItemModel nameModel = BaseItemModel(
        title: "Cave名称",
        hitString: "请输入Cave名称",
        requestKey: "",
        itemType: BaseItemTypeENUM.ENUM_InputCell);

    BaseItemModel typeModel = BaseItemModel(
        title: "申请类型",
        datas: [
          {'text': '个人Cave', 'value': 0},
          {'text': '官方Cave', 'value': 1}
        ],
        requestKey: "",
        itemType: BaseItemTypeENUM.ENUM_SelectTypeCell);

    BaseItemModel categoryModel = BaseItemModel(
        title: "申请分类",
        hitString: "请选择分类",
        requestKey: "",
        value: '',
        imageName: "vip_down",
        itemType: BaseItemTypeENUM.ENUM_SelectCell);

    BaseItemModel contextModel = BaseItemModel(
        title: "申请内容",
        hitString: "请详细说明创建的目的，如何完善自己的cave，未来发展方向等。",
        requestKey: "",
        itemType: BaseItemTypeENUM.ENUM_MoreInputCell);

    BaseItemModel attachmentModel = BaseItemModel(
        title: "证明材料",
        hitString: "附带全网自媒体账号粉丝数量或自身影响力或者某领域的专业性",
        requestKey: "",
        itemType: BaseItemTypeENUM.ENUM_AddCell);

    data.add(headModel);
    data.add(nameModel);
    data.add(typeModel);
    data.add(categoryModel);
    data.add(contextModel);
    data.add(attachmentModel);
    dataSource = data;
    update();
  }

  getPersonCategory() async {
    ResponseData responseData = await WhlApi.getCaveCategory.get({'type': 0});
    if (responseData.isSuccess()) {
      personCategory = responseData.data;
      update();
    }
  }

  getOfficialCategory() async {
    ResponseData responseData = await WhlApi.getCaveCategory.get({'type': 1});
    if (responseData.isSuccess()) {
      officialCategory = responseData.data;
      officialCategoryActive = responseData.data[0]['id'];
      update();
      getOfficialSecondCategory();
    }
  }

  getOfficialSecondCategory() async {
    ResponseData responseData = await WhlApi.getCaveCategory
        .get({'type': 1, 'parentId': officialCategoryActive});
    if (responseData.isSuccess()) {
      officialSecondCategory = responseData.data;
      update();
    }
  }

  createCave(BuildContext context) async {
    caveModel?.caveName = caveNameController.text;
    caveModel?.content = contentController.text;
    if (avatarUrl == null || avatarUrl?.isEmpty == true) {
      MyToast.show('请上传Cave头像');
      return;
    }
    if (caveNameController.text.isEmpty) {
      MyToast.show('请输入Cave名称');
      return;
    }
    if (caveModel?.caveCategories == null ||
        caveModel?.caveCategories?.isEmpty == true) {
      MyToast.show('请选择申请分类');
      return;
    }

    ResponseData responseData = await WhlApi.createCave.post({
      'id': caveModel?.id,
      'caveName': caveModel?.caveName,
      'caveImg': avatarUrl,
      'caveType': caveModel?.caveType,
      'caveCategories': caveModel?.caveCategories,
      'caveCategoriesDesc': caveModel?.caveCategoriesDesc,
      'content': caveModel?.content,
      'qualificationImages': caveModel?.qualificationImages
    });

    if (responseData.isSuccess()) {
      MyToast.show('创建成功');
      Navigator.pop(context, responseData.data);
    }
  }
}
